#include "list_demo.h"

LOS_DL_LIST stu_head;

static VOID stu_init(){
	printf("init stu list\n");
	LOS_ListInit(&stu_head);
}

static VOID stu_insert(UINT8 *name, UINT8 ch, UINT8 math){
	STU_DATA *tmp;

	printf("inser %s chinese %d math %d ...", name, ch, math);
	tmp = (STU_DATA *)malloc(sizeof(STU_DATA));
	tmp->chinese = ch;
	tmp->math = math;
	// 申请内存
	tmp->name = (UINT8 *)malloc(sizeof(name));
	if(tmp->name==NULL){
		printf("failed\n");
	}
	// 复制内容
	memcpy(tmp->name, name, sizeof(name));
	// 插入节点
	LOS_ListHeadInsert(&stu_head, &(tmp->s_list));
	printf("ok\n");
}

static VOID stu_query_by_name(UINT8 *name){
	STU_DATA *tmp;
	
	printf("query %s ...\n", name);
	// 遍历链表
	LOS_DL_LIST_FOR_EACH_ENTRY(tmp, &stu_head, STU_DATA, s_list){
		// 比较每个节点的name与入参是否相等
		if(strcmp(name, tmp->name)==0){
			printf("chinese %d, math %d\n", tmp->chinese, tmp->math);
		}
	}
	printf("query %s over\n", name);
}

static VOID stu_delete_by_name(UINT8 *name){
	STU_DATA *tmp, *node;

	printf("delete %s ...\n", name);
	// 遍历链表
	LOS_DL_LIST_FOR_EACH_ENTRY(tmp, &stu_head, STU_DATA, s_list){
		// 比较每个节点的name与入参是否相等
		if(strcmp(name, tmp->name)==0){
			// 找到当前节点的前驱
			node = LOS_DL_LIST_ENTRY(tmp->s_list.pstPrev, STU_DATA, s_list);
			// 删除节点
			LOS_ListDelete(&(tmp->s_list));
			// 释放内存
			free(tmp->name);
			free(tmp);
			// 由于当前节点被删除，因此tmp要重新赋值，这样tmp->s_list.pstNext才有效
			tmp = node;
		}
	}
	stu_query_by_name(name);
}

static VOID stu_modify_math(UINT8 *name, UINT8 math){
	STU_DATA *tmp;

	printf("modify %s math score...\n", name);
	// 遍历链表
	LOS_DL_LIST_FOR_EACH_ENTRY(tmp, &stu_head, STU_DATA, s_list){
		// 比较每个节点的name与入参是否相等
		if(strcmp(name, tmp->name)==0){
			// 更改数据
			tmp->math = math;
		}
	}
	// 重新查询，验证是否修改
	stu_query_by_name(name);
}

VOID list_entry(VOID){
	stu_init();
	stu_insert("David", 80, 92);
	stu_insert("Mars", 82, 94);
	stu_insert("Alex", 84, 96);
	stu_insert("Tom", 86, 97);
	stu_insert("Jerry", 88, 98);
	stu_query_by_name("Tom");
	stu_modify_math("Tom", 90);
	stu_delete_by_name("Jerry");
}

SYS_RUN(list_entry);
